package com.example.sys.async.task;

import com.example.sys.async.handler.ASyncHandler;
import com.example.sys.async.po.SysASync;
import com.example.sys.async.service.SysASyncService;
import org.springframework.context.ApplicationContext;

import java.util.Date;
import java.util.concurrent.CountDownLatch;

/***
 *
 * 线程池执行任务
 */
public class RunTask implements Runnable {

    private CountDownLatch countDownLatch;

    private SysASync sysASync;

    private ApplicationContext applicationContext;

    public CountDownLatch getCountDownLatch() {
        return countDownLatch;
    }

    public void setCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    public SysASync getSysASync() {
        return sysASync;
    }

    public void setSysASync(SysASync sysASync) {
        this.sysASync = sysASync;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run() {
        if (sysASync != null && !sysASync.isCompleted()) {
            SysASyncService sysASyncService = this.applicationContext.getBean(SysASyncService.class);
            ASyncHandler aSyncHandler = this.applicationContext.getBean(sysASync.getType().getHandler());
            sysASync.setStartTime(new Date());
            aSyncHandler.handler(sysASync);
            sysASync.setEndTime(new Date());
            sysASync.setCompleted(true);
            sysASyncService.saveOrUpdate(sysASync);
            countDownLatch.countDown();
        }
    }

    public RunTask(CountDownLatch countDownLatch, SysASync sysASync, ApplicationContext applicationContext) {
        this.countDownLatch = countDownLatch;
        this.sysASync = sysASync;
        this.applicationContext = applicationContext;
    }
}
